#pragma once
#include <string>
#include <map>
#include <vector>
#include <opencv2/opencv.hpp>
#include "color.h"
#include "ThreadPool.h"
#include "Dict.h"

using namespace std;

class ImageHost
{
public:
    ImageHost();
    ~ImageHost();

    long Capture(const std::wstring &file);

    void set_offset(int x1, int y1);

    long CmpColor(long x, long y, const std::wstring &scolor, double sim);

    long FindColor(const std::wstring &color, double sim, long dir, long &x, long &y);

    long FindPic(const std::wstring &files, const wstring &delta_colors, double sim, long dir, long &x, long &y);

    long FindPic(const std::wstring &files, double threshold, long &x1, long &y1, long &x2, long &y2);

    long LoadPic(const wstring &files);

    long FreePic(const wstring &files);

    long LoadMemPic(const wstring &file_name, void *data, long size);

    long UseDict(const wchar_t *dict_name);

    long ClearDict();

    long FindStr(const wstring &strs, double threshold, long &retx1, long &rety1, long &retx2, long &rety2);

    std::vector<std::wstring> Ocr(double threshold, std::vector<cv::Rect> &rects);

private:
    bool loadCurrDictMat(const wstring &word_str);

    // RETURN TYPE 0:word colors info; 1:bk color info
    int str2colordfs(const std::wstring &color_str, std::vector<color_df_t> &colors);

    void str2colors(const std::wstring &color, std::vector<color_t> &vcolor);

    void files2mats(const wstring &files, std::vector<cv::Mat> &vpic, std::vector<wstring> &vstr);

    cv::Mat getBinaryByCurrDict();
    // 加载字典数据通过单字模式
    bool loadDictsBySingleWord(const wstring &strs, std::vector<DictContent> &vdict);

    // 加载字典数据通过多字模式
    bool loadDictsByMultiWord(const wstring &strs, std::vector<DictContent> &vdict);

    // 查找字典图片
    bool findDictTemplate(cv::Mat &source, cv::Mat &templateImg, double threshold, std::vector<cv::Rect> &rects);

    cv::Rect matchDictTemplate(cv::Mat &source, const std::vector<DictContent> &vdict, double threshold = 0.8f);

    // 使用掩码的模板匹配
    cv::Rect findTemplateWithMask(cv::Mat &source, cv::Mat &templateImg, double threshold = 0.8);

    cv::Rect findTemplate(cv::Mat &source, cv::Mat &templateImg, double threshold = 0.8);

public:
    cv::Mat _src;

    // 当前目录
    wstring currPath_;

private:
    // 起始点
    int _x1, _y1;
    // 偏移
    int _dx, _dy;

    // 图片缓存
    std::map<wstring, cv::Mat> _pic_cache;

    ThreadPool m_threadPool;

    std::map<wstring, Dict> dicts_;

    Dict *currDict_ = nullptr;
};
